import * as mars3d from "mars3d"
import { Cesium } from "mars3d"
import { ref } from "vue"
import { useApiStore } from "../../pages/jcxm/stores/user"

export let map: any // mars3d.Map三维地图对象
export const eventTarget: mars3d.BaseClass = new mars3d.BaseClass()

/**
 * 初始化地图业务，生命周期钩子函数（必须）
 * 框架在地图初始化完成后自动调用该函数
 * @param {mars3d.Map} mapInstance 地图对象
 * @returns {void} 无
 */
export function onMounted(mapInstance: any): void {
  map = mapInstance // 记录map
  console.log(map)
  const underground = new mars3d.thing.Underground({
    alpha: 0.5,
    enabled: true,
    id: "underground"
  })
  map.addThing(underground)
  load3DTiles("新城区Mesh模型", "//122.9.68.70:6789/pingdingshan/xcq/tileset.json", "xcq")

  loadpipelinegeojson("WSLINE.geojson", "WSLINE", { color: "#00ffff", speed: 10, percent: 0.15, alpha: 0.2 })
  loadpipelinegeojson("YSLINE.geojson", "YSLINE", { color: "#506eff", speed: 10, percent: 0.15, alpha: 0.2 })
  // loadpipepointgeojson("WSPOINT.geojson","WSPOINT","#ff0000")
  // loadpipepointgeojson("YSPOINT.geojson","YSPOINT","#00ff2a")
  // loadGraphicPipe()
}

/**
 * 释放当前地图业务的生命周期函数
 * @returns {void} 无
 */
export function onUnmounted() {
  map = null
}

export function load3DTiles(name, url, id, position = {}) {
  const tilesLayer = new mars3d.layer.TilesetLayer({
    name: name,
    url: url,
    // center: { lat: 34.814603, lng: 113.551305, alt: 693.4, heading: 359.1, pitch: -43.5 },
    position: position,
    maximumScreenSpaceError: 1,
    dynamicScreenSpaceError: false,
    cullWithChildrenBounds: false,
    skipLevelOfDetail: false,
    preferLeaves: false,
    highlight: { type: "click", color: "#00ffff" },
    flyTo: false,
    id: id,
    show: true
  })
  tilesLayer.opacity = 0.8
  map.addLayer(tilesLayer)
  tilesLayer.readyPromise.then(function (layer) {
    console.log("load完成", layer)
    eventTarget.fire("load", map)
  })
  // 加载的事件 只执行一次
  tilesLayer.on(mars3d.EventType.initialTilesLoaded, function (event) {
    console.log("触发initialTilesLoaded事件", event)
  })

  // 会执行多次，重新加载一次完成后都会回调
  // tilesLayer.on(mars3d.EventType.allTilesLoaded, function (event) {
  //   console.log("触发allTilesLoaded事件", event)
  // })
}

export function loadGraphicPipe() {
  const graphicLayer = new mars3d.layer.GraphicLayer({
    id: "pipe",
    name: "管道",
    show: true,
    center: { lat: 34.791948, lng: 113.534755, alt: 396.3, heading: 359.1, pitch: -43.5 }
  })
  const graphic1 = new mars3d.graphic.PolylineVolumeEntity({
    positions: [
      [113.525275, 34.795023, 80],
      [113.565093, 34.795202, 80]
    ],
    style: {
      shape: "pipeline",
      radius: 2,
      cornerType: Cesium.CornerType.BEVELED,
      materialType: mars3d.MaterialType.LineFlow,
      materialOptions: {
        color: "#3388ff",
        image: "img/textures/fence-line.png",
        speed: 10,
        repeat_x: 6
      }
    },
    attr: { name: "雨水管道", type: "雨水", id: "1230002", state: "正常" },
    popup: [
      { field: "name", name: "名称" },
      { field: "id", name: "编码" },
      { field: "type", name: "类型" },
      { field: "state", name: "状态" }
    ]
    // attr: "all",
  })
  graphicLayer.addGraphic(graphic1)
  const graphic2 = new mars3d.graphic.PolylineVolumePrimitive({
    positions: [
      [113.525261, 34.795096, 80],
      [113.56508, 34.795275, 80]
    ],
    style: {
      shape: "pipeline",
      radius: 2,
      // color: "#2bff50",
      cornerType: Cesium.CornerType.BEVELED,
      materialType: mars3d.MaterialType.LineFlow,
      materialOptions: {
        color: "#00ffff",
        image: "img/textures/fence-line.png",
        speed: 10,
        repeat_x: 6,
        alpha: 0.5
      }
    },
    attr: { name: "污水管道", type: "污水", id: "1230001", state: "正常" },
    popup: [
      { field: "name", name: "名称" },
      { field: "id", name: "编码" },
      { field: "type", name: "类型" },
      { field: "state", name: "状态" }
    ]
    // attr: "all",
  })
  graphicLayer.addGraphic(graphic2)

  const graphic3 = new mars3d.graphic.BillboardEntity({
    name: "贴地点",
    position: [113.537735, 34.795072, 83.7],
    style: {
      image: "img/marker/point-yellow.png",
      scale: 1,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM
    },
    attr: { name: "雨水井盖", type: "雨水", id: "1230011", state: "正常" }
  })
  graphic3.bindPopup((event: any) => {
    const attr = event.graphic.attr
    return mars3d.Util.getTemplateHtml({ title: "井盖", template: "all", attr })
  })
  graphicLayer.addGraphic(graphic3)
  // const graphic3 = new mars3d.graphic.RectanglePrimitive({
  //   positions: [
  //     [113.536404, 34.795133],
  //     [113.536453, 34.795169]
  //   ],
  //   style: {
  //     height: 85,
  //     image: "img/JingGai.png"
  //   }
  // })
  // graphicLayer.addGraphic(graphic3)
  map.addLayer(graphicLayer)
}

export function loadpipelinegeojson(url, id, materialOptions = {}) {
  const geojsonLayer = new mars3d.layer.GeoJsonLayer({
    name: "管道",
    url: "//122.9.68.70:6789/pipejson/" + url,
    id: id,
    show: true,
    symbol: {
      type: "polylineVolume",
      styleOptions: {
        shape: "circle",
        radius: 2,
        cornerType: Cesium.CornerType.BEVELED,
        materialType: mars3d.MaterialType.LineFlowColor,
        materialOptions: materialOptions
      }
    },
    popup: "all"
  })
  map.addLayer(geojsonLayer)
}

export function loadpipepointgeojson(url, id, color = "#ff0000") {
  const geojsonLayer = new mars3d.layer.GeoJsonLayer({
    name: "管道",
    url: "//192.168.0.127:6789/pipejson/" + url,
    id: id,
    show: true,
    symbol: {
      type: "point",
      styleOptions: {
        pixelSize: 10,
        outline: false,
        outlineWidth: 2,
        color: color
      }
    },
    popup: "all"
  })
  map.addLayer(geojsonLayer)
}

export function loadpoint() {
  const graphicLayer = new mars3d.layer.GraphicLayer({
    id: "beidouSys",
    allowDrillPick: false
  })
  map.addLayer(graphicLayer)
  const graphic = new mars3d.graphic.BillboardEntity({
    position: [113.537945, 34.796747, 93.6],
    style: {
      image: "img/marker/mark-blue.png",
      scale: 1,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM
    },
    show: true
  })
  graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(PointLayer)
  Popup(graphic)
}

function Popup(graphic) {
  graphic.bindPopup(
    function (event) {
      const apiStore1 = useApiStore()
      let attr = ref({})
      attr.value = {
        状态: "采集中",
        经度: "113.537945",
        纬度: "34.796747",
        高程: "93.6",
        雨量: apiStore1.data[0].sRealTimeValue + "mm",
        振弦频率: apiStore1.data[4].sRealTimeValue + "hz",
        振弦温度: apiStore1.data[5].sRealTimeValue + "℃",
        土壤湿度: apiStore1.data[1].sRealTimeValue + "%",
        土壤温度: apiStore1.data[2].sRealTimeValue + "℃"
      }
      let attrKey = Object.keys(attr.value)
      let container: Element = document.createElement("div")
      container.innerHTML = popupHtml
      let titlelogo = container.querySelector("#title-logo")
      let title = container.querySelector("#title")
      title.innerHTML = "传感器"
      let table = container.querySelector("#content") as HTMLElement
      for (let i = 0; i < attrKey.length; i++) {
        let row = document.createElement("div")
        row.style.cssText = "display: flex;align-items: center;font-size: 14px;margin-bottom: 10px;"
        let colid = "t" + (i + 1)
        row.setAttribute("id", colid)
        table.append(row)
        let col1 = document.createElement("div")
        col1.style.cssText = "width: 40%;color:#51d4ff;font-size:14px;text-align: left;"
        col1.setAttribute("id", colid + 1)
        col1.innerHTML = attrKey[i]
        row.append(col1)
        let col2 = document.createElement("div")
        col2.style.cssText = "width: 60%;font-size:14px;color: #FFFFFF;text-align: right;"
        col2.setAttribute("id", colid + 2)
        col2.append((document.createElement("p").innerHTML = attr.value[attrKey[i]]))
        row.append(col2)
      }
      return container
    },
    { offsetY: -35 }
  )
}

// 显示变化*****************
// setInterval(function () {
//   let num = document.querySelector("#t62")
//   if (num) {
//     num.innerHTML = ((1540.83 + Math.random() * 0.1).toFixed(3)).toString() + "hz"
//   }
// }, 10000)
let popupHtml = `<div id="popuproot" style="border-radius: 3px;padding: 15px;text-align: left;background-color: rgba(0,0,0,0.8);background-size: cover;width: 300px;">
  <div id="popup-box" style="width:auto;">
  <div id="popup-head" style="display: flex;align-items: center;">
    <img id="title-logo" src="" alt="" style="margin-right: 10px;">
    <div id="title" style="color: #ffffff;font-size: 16px;text-align: left;vertical-align: middle;"></div>
  </div>
    <div id="content" style="margin: 2px; width: 95%;">
    </div>
  </div>
</div>
`
